package com.iflytek.uoamp.agent.monitor.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.iflytek.uoamp.agent.monitor.sender.config.Config;
import com.iflytek.uoamp.agent.monitor.sender.config.HostInfo;

public class PropertiesHelper {

	private static Map<String, Config> configMap = new HashMap<String, Config>();

	private static Properties prop = new Properties();

	private static List<HostInfo> getHostInfoFromString(String hostString) throws Exception {
		List<HostInfo> hostsList = new ArrayList<HostInfo>();
		String[] hostsString = hostString.split(" ");
		for (int i = 0; i < hostsString.length; i++) {
			String[] tmps = hostsString[i].split(":");
			if (tmps.length != 2 && tmps.length != 3) {
				throw new Exception("error flume agent config");
			}
			HostInfo curHostInfo = null;
			if (tmps.length == 3) {
				curHostInfo = new HostInfo(hostsString[i], tmps[0], Integer.parseInt(tmps[1]), Integer.parseInt(tmps[2]));
			} else {
				curHostInfo = new HostInfo(hostsString[i], tmps[0], Integer.parseInt(tmps[1]), Integer.parseInt("1"));
			}
			if (contains(hostsList, curHostInfo) == true) {
				hostsList.get(position(hostsList, curHostInfo)).addWeight(curHostInfo.getHostWeight());
			} else {
				hostsList.add(curHostInfo);
			}
		}
		return hostsList;
	}

	private static boolean contains(List<HostInfo> list, HostInfo host) {
		boolean ret = false;
		for (HostInfo hostInfo : list) {
			if (hostInfo.Identity().equals(host.Identity()) == true) {
				ret = true;
			}
		}
		return ret;
	}

	private static int position(List<HostInfo> list, HostInfo host) {
		int ret = 0;
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).Identity().equals(host.Identity()) == true) {
				ret = i;
			}
		}
		return ret;
	}

	/**
	 * 获取公共的链接配置
	 * @param configPath
	 * @return
	 */
	public synchronized static Config getCientConfig(String configPath) {
		if (configMap.containsKey(configPath)) {
			return configMap.get(configPath);
		}
		
		Config config = new Config();
		InputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(configPath));
			prop.load(in);
			config.setCachePath(prop.getProperty("cache_path", ""));
			config.setConnectTimeOut(Integer.parseInt(prop.getProperty("connect_timeout", "20000")));
			config.setRequestTimeOut(Integer.parseInt(prop.getProperty("request_timeout", "20000")));
			config.setSendQueueSize(Integer.parseInt(prop.getProperty("send_queue_size", "20000")));
			config.setPingIntervalTime(Integer.parseInt(prop.getProperty("ping_interval_time", "3000")));
			config.setPingTimeOut(Integer.parseInt(prop.getProperty("ping_timeout", "15000")));
			config.setSchedualIntervalTime(Integer.parseInt(prop.getProperty("schedual_interval_time", "-1")));
			config.setUseHttp(prop.getProperty("use_http", "true").equals("true") ? true : false);
			config.setIsUseSafeMod(prop.getProperty("use_safe_mode", "true").equals("true") ? true : false);
			config.setSchedualIntervalTime(Integer.parseInt(prop.getProperty("schedual_interval_time", "300")));
			config.setFirstIntervalDelay(Integer.parseInt(prop.getProperty("first_sche_delay", "300")));
			config.setConnectPoolSize(Integer.parseInt(prop.getProperty("connect_pool_size", "10")));
			String servertarget = prop.getProperty("server_target", "");
			// 为了避免配置文件未升级带来问题，此处将agent作为配置项时的逻辑保留
			if (StringUtils.isBlank(servertarget)) {
				servertarget = prop.getProperty("agent", "127.0.0.1:18185");
			}
			config.setHostInfo(getHostInfoFromString(servertarget));
			config.setNoTranferFillPercentage(Integer.parseInt(prop.getProperty("no_transfer_fill_percentage", "50")));
			config.setUrl(prop.getProperty("http_url", "http://127.0.0.1:8080/"));
			configMap.put(configPath, config);
		} catch (Exception e) {
			Logger.getRootLogger().error(e.getMessage(),e);
		}finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					Logger.getRootLogger().error(e.getMessage(),e);
				}
			}
		}
		return configMap.get(configPath);
	}

}
